// pages/test/test.js
const app = getApp()
const myaudio = wx.createInnerAudioContext();
var init;
var intetimes;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    millisecond1: 0,
    millisecond: 0,
    frameWidth: 0,
    frameHeight: 0,
    pixelRatio: 2,
    windowWidth: 0,
    windowHeight: 0,
    screenHeight: 100,
    utime: 0,
    index: 0,
    jinru: false,
    scan: {
      width: 0,
      height: 0,
      top: 0
    },
    isplay: false, //是否播放
    time: false, //判断是否执行createCameraContext方法
    state: false,
    yfyindex:0,
    msg:''
  },
  doback: function() {
    wx.navigateBack({
      delta: 1
    })
  },
  test2: function() {
    this.data.utime = 0;
  },
  getMoreData: function(b) {
    var array = new Uint8Array[8];
    for (var i = 7; i >= 0; i--) {
      array[i] = (b & 1);
      b = (b >> 1);
    }
    return array;
  },
  test3: function() {
    app.globalData.canuse = false;
    wx.chooseImage({
      count: 1,
      sizeType: ['original'],
      sourceType: ['album'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths
        //console.log(tempFilePaths[0]);
        var en = tempFilePaths[0].lastIndexOf(".jpg");
        var isJPG = (en > -1 && en == tempFilePaths[0].length - 4);
        wx.getFileSystemManager().readFile({
          encoding: isJPG ? "base64" : "",
          filePath: tempFilePaths[0],
          success: (res) => {
            var isStr = (typeof res.data == 'string') && res.data.constructor == String;
            var s = res.data;
            if (!isStr) {
              var x1 = new Uint8Array(res.data);
              // console.log("获取到数据", res.data.byteLength, res.data, x1)
              var x2 = new Uint8Array(256 * 360);
              var temarr = [];
              console.log("数据长度", x1.byteLength);
              var uindex = 256 * 360 - 1;
              for (var a = 0; a < x1.byteLength; a++) {
                if (a < 62) {
                  continue;
                }
                // var aaa = this.getMoreData(res.data[a]);
                var b = x1[a];
                var array = [];
                for (var i = 7; i >= 0; i--) {
                  array[i] = (b & 1) * 255;
                  b = (b >> 1);
                }
                temarr.push.apply(temarr, array);
                if (temarr.length == 256) {
                  for (var i = temarr.length - 1; i >= 0; i--) {
                    x2[uindex] = temarr[i];
                    uindex--;
                  }
                  temarr = [];
                }
              }
              s = wx.arrayBufferToBase64(x2)
              console.log(s)
            }
            wx.request({
              // url: app.globalData.the_host + '/newcode/api/scan2.htm',
              url: app.globalData.the_host + '/productfcode/scan',
              data: {
                "code": s,
                "width": 256,
                "isJPG": isStr ? 1 : 0,
                "openId": '1', //app.globalData.openId,
                "province": app.globalData.province ? app.globalData.province : "",
                "city": app.globalData.city ? app.globalData.city : "",
                "address": app.globalData.county,
                "lat": app.globalData.lat,
                "lng": app.globalData.lng,
              },
              // header: {
              //   'content-type': 'application/x-www-form-urlencoded' // 默认值
              // },
              header: {
                'content-type': 'application/json'
              },
              method: "POST",
              success: res => {
                // console.log(s);
                console.log("收到服务器返回：我是手动")
                if (res.statusCode == 200) {
                  console.log(res.data)
                  if (res.data.status == 0) {
                    // wx.showToast({
                    //   title: `成功！`,
                    //   icon: 'success',
                    //   duration: 2000
                    // })

                    // console.log("收到服务器返回", res.data.data.pcode, res.data.data.code)
                    const innerAudioContext = wx.createInnerAudioContext()
                    innerAudioContext.autoplay = true
                    innerAudioContext.src = app.globalData.the_host + '/image/sound/5383.mp3'
                    innerAudioContext.onPlay(() => {
                      console.log('开始播放')
                    })
                    innerAudioContext.onError((res) => {
                      console.log(res.errMsg)
                      console.log(res.errCode)
                    })
                    innerAudioContext.onEnded((res1) => {
                      console.log('播放结束!');
                      let code = JSON.stringify(res.data.data)
                      //console.log(code)
                      wx.navigateTo({
                        url: '../webview/index?code=' + code
                      })
                    })
                  } else {

                    wx.showToast({
                      title: `失败`,
                      icon: 'success',
                      duration: 2000
                    })
                  }
                }
                app.globalData.canuse = true
              }
            })
          }
        });


        console.log(tempFilePaths)

      },
      fail() {
        app.globalData.canuse = true;
      },
      complete() {
        // console.log(22)
      }
    })
  },

  test: function() {
    var that = this;
    if (this.data.windowWidth == 0) {
      wx.getSystemInfo({
        success: (res) => {
          // console.log(res.model)
          // console.log(res.pixelRatio)
          // console.log(res.windowWidth)
          // console.log(res.screenWidth)
          // console.log(res.screenHeight)
          // console.log(res.windowHeight)
          // console.log(res.language)
          // console.log(res.version)
          // console.log(res.platform)
          // this.windowWidth  = res.windowWidth;
          // this.windowHeight = res.windowHeight;

          // console.log("活的aaa", this.windowWidth, this.windowHeight)


          this.setData({
            windowWidth: res.windowWidth,
            windowHeight: res.windowHeight,
            pixelRatio: res.pixelRatio,
            screenHeight: res.screenHeight

          });

          console.log("获取到窗口宽高" + res.windowWidth, res.windowHeight, res.screenHeight, res.pixelRatio)

        }
      })
    }
    wx.authorize({
      scope: "scope.camera"
    })
    console.log("开始001")
    const context = wx.createCameraContext()
    this.data.cameraListener = context.onCameraFrame((frame) => {
      if (this.data.frameWidth == 0) {
        var uwidth = 256 * this.data.windowWidth / frame.width;
        var uheight = 360 / 256 * uwidth;
        console.log("width:" + this.data.windowWidth)
        this.setData({
          fheight: frame.height,
          fwidth: frame.width,
          time: true,
        });
        if (frame.height < frame.width) {
          this.setData({
            jinru: true
          });
          // uwidth / 256  = this.data.windowWidth / frame.height
          uwidth = 256 * this.data.windowWidth / frame.height;
          uheight = 360 / 256 * uwidth;
        }
        if (frame.height < frame.width) {
          if (this.data.windowWidth * this.data.pixelRatio > frame.width) {
            uwidth = this.data.windowWidth * this.data.pixelRatio / frame.height * uwidth

            uheight = this.data.windowWidth * this.data.pixelRatio / frame.height * uheight
          }
        }
        if (frame.height == 960 && frame.width == 720) {
          uwidth = uwidth * 1.45
          uheight = uheight * 1.45
        }
        var utop = this.data.screenHeight / 2 - uheight;
        var uleft = (this.data.windowWidth - uwidth) / 2
        if (frame.height == 960 && frame.width == 720) {
          utop = utop + 10
        }
        this.setData({
          frameWidth: frame.width,
          frameHeight: frame.height,
          scan: {
            width: uwidth,
            height: uheight,
            top: utop,
            left: uleft
          }
        });
        // console.log(frame.data instanceof ArrayBuffer, frame.width, frame.height)  
      }
      if (this.data.utime == 0) {
        console.log("开始取帧")

        // this.startvoice()
      }

      if (this.data.utime % 50 == 0 && !app.globalData.loading && app.globalData.canuse) {
        var a = this.data.index + 1;
        this.setData({
          index: a,
        });
        console.log(this.data.index)
        app.globalData.loading = true;
        //console.log("取到", new Date())
        // console.log("获得到数据", frame.data.byteLength, this.data.frameWidth, this.data.frameHeight, this.data.windowWidth, this.data.windowHeight)
        var nw = 256,
          nh = 360;
        //计算

        if (this.data.frameHeight < this.data.frameWidth) {
          console.log("我们这很奇怪")
          // 256 / x = this.data.frameHeight / this.data.frameWidth;
          nw = parseInt(256 / (this.data.frameHeight / this.data.frameWidth))

          // 360 / y = this.data.frameWidth / this.data.frameHeight;
          nh = parseInt(360 / (this.data.frameWidth / this.data.frameHeight));
        }

        // console.log()
        var x1 = new Uint8Array(frame.data);
        // var x2 = new Uint8Array(frame.data.byteLength/4);
        var x2 = new Uint8Array(nw * nh);
        // 计算x,y的范围
        var startx = (this.data.frameWidth - nw) / 2;
        var endx = startx + nw;
        var starty = this.data.frameHeight / 2 - nh;
        console.log("startx:this.data.frameWidth / 2 - nw:" + startx)
        console.log("starty:this.data.frameHeight / 2 - nh:" + starty)
        //console.log("frameHeight:" + this.data.frameHeight)
        //console.log("frameWidth:" + this.data.frameWidth)
        if (app.globalData.isHuaWei) {
          // starty = starty + 26 * this.data.pixelRatio
          starty = starty + 8 * this.data.pixelRatio
          // starty = starty + 40
          // / this.data.screenHeight * this.data.frameHeight + 30
          // + 26 * this.data.pixelRatio/ this.data.screenHeight * this.data.frameHeight
        } else {
          starty = starty + 9 * this.data.pixelRatio
        }
        // if (this.data.frameHeight < this.data.frameWidth){
        //   starty = this.data.frameHeight / 8 + (64 / (this.data.windowHeight + 64) * this.data.frameHeight);
        // }
        // if (app.globalData.isHuaWei){
        this.setData({
          "isHuaWei": app.globalData.isHuaWei
        });
        this.setData({
          "starty": starty
        });
        var endy = starty + nh;
        // console.log(startx, endx, starty, endy)
        var arr = [];
        var uindex = 0;
        for (var a = 0; a < x1.length; a++) {
          var yu = (a + 1) % 4;
          if (yu != 0) {
            arr[yu - 1] = x1[a];
          } else {
            var y = parseInt(parseInt(a / 4 + 1) / this.data.frameWidth);
            var x = parseInt(parseInt(a / 4 + 1) % this.data.frameWidth);
            if (x < startx || x >= endx || y < starty || y >= endy) {
              continue;
            }
            x2[uindex] = parseInt((arr[0] * 30 + arr[1] * 59 + arr[2] * 11) / 100)
            uindex++;
          }
        }
        var s = wx.arrayBufferToBase64(x2)
        // console.log("收到服务器返回：自动",s)
        //console.log("收到服务器返回自动:"+s )
        //将图像专程base64传到服务器
        // this.start()
        wx.request({
          url: app.globalData.the_host + '/fcode/decode',
          //url: app.globalData.the_host + '/newcode/api/scan2.htm',
          data: {
            "code": s,
            "width": nw,
            "isJPG": 0,
            // "openId": '1',//app.globalData.openId,
            // "province": app.globalData.province ? app.globalData.province : "",
            // "city": app.globalData.city ? app.globalData.city : "",
            // "address": app.globalData.county,
            // "lat": app.globalData.lat,
            // "lng": app.globalData.lng,
          },
          // header: {
          //   'content-type': 'application/x-www-form-urlencoded' // 默认值
          // },
          header: {
            'content-type': 'application/json'
          },
          method: "POST",
          success: function(res) {
            if (res.statusCode == 200) {
              that.stop();
              if (that.data.state == false) {
                // console.log(res.data.message)
                if (res.data.status == 0 || res.data.status == 30) {
                  app.globalData.loading = true;
                  that.onstop() //停止提示播放                  
                  that.setData({
                    state: true,
                    yfyindex: that.data.yfyindex+1,
                    msg: res.data.message
                  })
                  // console.log("收到服务器返回", res.data.data.pcode, res.data.data.code)
                  const innerAudioContext = wx.createInnerAudioContext()
                  innerAudioContext.autoplay = true
                  innerAudioContext.src = app.globalData.the_host + '/image/sound/5383.mp3'
                  innerAudioContext.onPlay(() => {
                    console.log('开始播放')
                  })
                  innerAudioContext.onError((res) => {
                    console.log(res.errMsg)
                    console.log(res.errCode)
                  })
                  innerAudioContext.onEnded((res1) => {
                    console.log('播放结束!');
                    //let code = JSON.stringify(res.data.data)
                    //console.log(code)
                    wx.showToast({
                      title: res.data.message,
                      icon: 'success',
                      duration: 2000
                    })
                    clearInterval(intetimes);
                    if (res.data.status == 30) {
                      wx.redirectTo({
                        url: '../tips/index?status=30&fcode=1&vcode=1'
                      })
                    } else {
                      wx.redirectTo({
                        url: '../tips/index?fcode=' + res.data.data.fcode + "&vcode=" + res.data.data.vcode
                      })
                    }
                    
                  })
                } else {
                  that.setData({
                    millisecond1: res.data.elapsedTime,
                    msg: res.data.message
                  })
                  app.globalData.loading = false;
                }
              }
            } else {
              that.stop()
              console.log("收到服务器返回" + res.statusCode)
              app.globalData.loading = false;
            }

          }
        })
      } else {
        this.stop()
      }
      this.data.utime = this.data.utime + 1;
    })
    this.data.cameraListener.start()
    setTimeout(() => {
      if (!this.data.time) {
        wx.showToast({
          title: '手机版本过低',
          icon: 'success',
          duration: 3000,
          success: function() {
            setTimeout(function() {
              //this.data.cameraListener.stop()
              clearInterval(intetimes);
              wx.switchTab({
                url: '../index/index'
              })
            }, 2000) //延迟时间 
          }
        })
      }
      // console.log('10秒了！' + this.data.time)
    }, 5000)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.getNetworkType({
      success: function (res) {
        if (res.networkType == "none") {
          wx.showModal({
            title: '提示',
            content: '没有网络连接,请检查您的网络设置',
            showCancel: false,
          })
        } else if (res.networkType == "2g" || res.networkType == "3g") {
          wx.showModal({
            title: '提示',
            content: '网络信号差…',
            showCancel: false,
          })
        } else if (res.networkType == "unknown") {
          wx.showModal({
            title: '提示',
            content: '未知的网络类型,请检查您的网络设置',
            showCancel: false,
          })
        }
      },
      fail: function (err) {
        wx.showModal({
          title: '提示',
          content: '访问错误',
          showCancel: false,
        })
      }
    })
    wx.onWindowResize(function(res) {
      console.log("尺寸变化", res)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    app.globalData.loading = false;
    this.onstart() //开始播放
    console.log("onReady")
    clearInterval(intetimes);
    intetimes = setInterval(function() {
      wx.showToast({
        title: '扫码超时',
        icon: 'success',
        duration: 3000,
        success: function() {
          setTimeout(function() {
            //this.data.cameraListener.stop()
            clearInterval(intetimes);
            wx.switchTab({
              url: '../index/index'
            })
          }, 2000) //延迟时间 
        }
      })
    }, 20000);
    //this.test()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.onstart() //开始播放
    myaudio.src = app.globalData.the_host + '/image/sound/ScanSound.mp3'
    if (this.data.cameraListener) {
      this.data.cameraListener.start();
      // this.data.canuse = true;
    };

    setTimeout(() => {
      this.test()
    }, 500)

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    this.data.cameraListener.stop()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    app.globalData.loading = true;
    this.setData({
      state: true
    })
    this.onstop();
    this.data.cameraListener.stop()
    clearInterval(intetimes);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  //开始播放音乐
  onstart: function() {
    myaudio.play();
    console.log(myaudio.duration);
    this.setData({
      isplay: true
    });

  },
  //停止播放
  onstop: function() {
    console.log('播放结束!12')
    myaudio.stop();
    this.setData({
      isplay: false
    });
  },

  //-----------------计时器--------------------
  //开始
  start: function() {
    clearInterval(init);
    var that = this;
    that.setData({
      millisecond: 0,
      millisecond1: 0
    })
    init = setInterval(function() {
      that.timer()
    }, 50);
  },
  //暂停
  stop: function() {
    clearInterval(init);
  },
  //执行时间
  timer: function() {
    var that = this;
    console.log(that.data.millisecond)
    that.setData({
      millisecond: that.data.millisecond + 50
    })
  },

})